<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>upload</title>
    <link rel="stylesheet" href="../lib/bootstrap.css">
    <script src="../lib/jquery.js"></script>
</head>

<body>
    <input type="file" id="file1"/>
    <button>上传文件</button> 
    
    <div class="progress" style="width: 500px; margin: 15px 10px;">
        <div class="progress-bar progress-bar-striped active" style="width: 0%" id="percent">
          0%
        </div>
      </div>
    
    <img src="" alt="" id="img" width="800" />
    <script>
        var btn = document.querySelector("button");
        btn.addEventListener("click", function () {
            var files = document.querySelector('#file1').files;
            if (files.length <= 0) return alert("请选择要上传的文件")
            var fd = new FormData()
            // 将用户选择的文件，添加到 FormData 中
            fd.append('avatar', files[0])

            var xhr = new XMLHttpRequest()
           // 监听文件上传的进度
       // 监听文件上传的进度
       xhr.upload.onprogress = function (e) {
        if (e.lengthComputable) {
          // 计算出上传的进度
          var percentComplete = Math.ceil((e.loaded / e.total) * 100)
          console.log(percentComplete)
          // 动态设置进度条
          $('#percent').attr('style', 'width: ' + percentComplete + '%;').html(percentComplete + '%')
        }
      }

      xhr.upload.onload = function () {
        $('#percent').removeClass().addClass('progress-bar progress-bar-success')
      }
            xhr.open('post', 'http://www.liulongbin.top:3006/api/upload/avatar')
            xhr.send(fd)
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var data = JSON.parse(xhr.responseText)
                    console.log(data);
                    if (data.status===200){
                        document.querySelector("img").src='http://www.liulongbin.top:3006'+data.url
                    }else{
                        console.log('图片上传失败'+data.message);
                    }
                }
            }
        })
    </script>
</body>

</html>